package com.bxd.baodan.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.item.AnswerDetailBean;
import com.bxd.baodan.item.AnswerDetailBean.AnsInfoBean.FollowUpBean;
import com.bxd.baodan.item.QAStatus;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.widget.MyTextWatcher;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;


/*
推送消息需要加上PARENT_ACTIVITY,不然点击通知消息后会退出app
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activity.MainActivity"/>

*/
public class AnswerDetailActivity extends BaseListActivity_<FollowUpBean> {
    private ViewGroup headerView;
    private TextView ans_name, ans_content, ans_time, ans_caina, ans_zan_count;
    private ImageView ans_avatar, ans_verify, ans_zan_iv, ans_best_iv, official_iv;
    private boolean isSelf;
    private String qid;
    private String qaid;
    private EditText mEditText;

    private TextView add;
    boolean scrollToEnd;
    TextView title;
    View addLy;
    private TextView qes_content, ans_count;
    private BroadcastReceiver receiver;

    public QAStatus qaStatus = new QAStatus();


    TextView robotName, robotTime, robotContent;
    CheckBox robot_useful, robot_useless;

    View agent_ly, robot_ly;

    @Override
    protected int getActivityLayout() {
        return R.layout.activity_answer_detail;
    }


    @Override
    protected void preDone() {
        title = findViewById(R.id.bar_tv_title);

        title.setText("回答详情");

        findViewById(R.id.bar_iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        qid = getIntent().getStringExtra("qid");
        qaid = getIntent().getStringExtra("qaid");


        mEditText = (EditText) findViewById(R.id.et);

        add = (TextView) findViewById(R.id.add);

        addLy = findViewById(R.id.add_ly);
        if (LoginInfo.getInstance().isLogin()) {
            addLy.setVisibility(View.VISIBLE);
        } else {
            addLy.setVisibility(View.GONE);
        }

        setListener();
        setBroadCast();
        autoRefresh();
    }

    private void setBroadCast() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent data) {
                // TODO: 18/2/9 判断qid,相同就刷新
              //  if (Constant.QUESTION_TO_ANSWER.equals(data.getAction())) {
                    QAStatus status = (QAStatus) data.getExtras().getSerializable("qaStatus");
                    if (!status.qid.equals(qid)) {
                        return;
                    }
                    qaStatus = status;
                    showStatus(qaStatus);
              //  }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.QUESTION_TO_ANSWER);
        filter.addAction(Constant.ANSWER_TO_QUESTION);
        this.registerReceiver(receiver, filter);
    }

    @Override
    protected void addHeadView() {
        super.addHeadView();
        headerView = (ViewGroup) View.inflate(this, R.layout.answer_detail_header_new, null);

        robot_ly = headerView.findViewById(R.id.robot_layout);

        agent_ly = headerView.findViewById(R.id.agent_layout);
        robot_ly.setVisibility(View.GONE);
        agent_ly.setVisibility(View.GONE);

        listView.addHeaderView(headerView);
        ans_name = (TextView) headerView.findViewById(R.id.ans_name);
        ans_content = (TextView) headerView.findViewById(R.id.ans_content);
        ans_time = (TextView) headerView.findViewById(R.id.ans_time);
        ans_avatar = (ImageView) headerView.findViewById(R.id.ans_avatar);
        ans_verify = (ImageView) headerView.findViewById(R.id.ans_verify);
        official_iv = (ImageView) headerView.findViewById(R.id.official_iv);
        ans_caina = (TextView) headerView.findViewById(R.id.ans_caina);
        ans_zan_count = (TextView) headerView.findViewById(R.id.ans_zan_count);
        ans_zan_iv = (ImageView) headerView.findViewById(R.id.ans_zan_iv);
        ans_best_iv = (ImageView) headerView.findViewById(R.id.ans_best_iv);


        qes_content = (TextView) headerView.findViewById(R.id.qes_content);
        ans_count = (TextView) headerView.findViewById(R.id.ans_count);


        robotName = headerView.findViewById(R.id.robot_name);
        robotTime = headerView.findViewById(R.id.robot_ans_time);
        robotContent = headerView.findViewById(R.id.robot_content);
        robot_useful = headerView.findViewById(R.id.robot_useful);
        robot_useless = headerView.findViewById(R.id.robot_useless);


        setClick();

    }


    @Override
    protected void setNullPage(boolean isNullPage) {
        //空实现,不加载
    }

    private void setListener() {

        mEditText.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                String content = mEditText.getText().toString();
                if (StringUtil.isEmpty(content)) {
                    add.setTextColor(getResources().getColor(R.color.gray));
                    add.setClickable(false);
                } else {
                    add.setTextColor(getResources().getColor(R.color.green_lab));
                    add.setClickable(true);
                }
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(mEditText.getText().toString())) {
                    return;
                }

                MobclickAgent.onEvent(App.getContext(), "v6_1_3_BW_wdxq_pl_fs");
                NetUtil netUtil = new NetUtil(AnswerDetailActivity.this, JsonApi.ANSWER_EXTENDADD);
                netUtil.setParams("qid", qid);
                netUtil.setParams("qaid", qaid);
                netUtil.setParams("content", mEditText.getText().toString());
                netUtil.postRequest("", new NetUtil.RequestStringListener() {
                    @Override
                    public void onComplete(String result) {
                        scrollToEnd = true;
                        autoRefresh();
                        mEditText.setText("");

                    }
                });
            }
        });


    }

    @Override
    protected String getArrayStr(String json_data) {
        final AnswerDetailBean.AnsInfoBean bean = new Gson().fromJson(json_data, AnswerDetailBean.AnsInfoBean.class);

        //questionUid为提问者的uid
        isSelf = LoginInfo.getInstance().getUid().equals(bean.questionUid);

        qaStatus = new QAStatus(bean.isLike, bean.isDislike,
                bean.qqa_dislike, bean.qqa_like,
                qid, qaid,
                bean.qqa_isBestAnswer, bean.hasBestAnswer,
                bean.qqa_src);

        Runnable runnable = new Runnable() {
            public void run() {

                qes_content.setText(bean.qqd_title);
                ans_count.setText("查看" + bean.qq_answerCount + "个回答");
                ans_count.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(AnswerDetailActivity.this, QuestionDetailActivity.class);
                        intent.putExtra("qid", bean.qq_id);
                        startActivity(intent);
                    }
                });

                if (qaStatus.src.equals("6")) {
                    robot_ly.setVisibility(View.VISIBLE);
                    agent_ly.setVisibility(View.GONE);
                    parseRobot(bean);
                    addLy.setVisibility(View.GONE);
                } else {
                    robot_ly.setVisibility(View.GONE);
                    agent_ly.setVisibility(View.VISIBLE);
                    showStatus(qaStatus);
                    showDefault(bean);
                    addLy.setVisibility(View.VISIBLE);
                }

            }
        };
        runOnUiThread(runnable);

        String list = JSONUtil.getArrayData("followUp", json_data);


        return list;
    }

    private void showDefault(final AnswerDetailBean.AnsInfoBean bean) {


        GlideUtil.loadCircle(getApplicationContext(), bean.u_avatar, ans_avatar);
        ans_name.setText(bean.u_nick);
        //认证
        if (bean.agent_mark != null && bean.agent_mark.length > 0
                && Arrays.asList(bean.agent_mark).contains("6")) {
            ans_verify.setVisibility(View.VISIBLE);
        } else {
            ans_verify.setVisibility(View.GONE);
        }
        //官方顾问
        if (bean.agent_mark != null && bean.agent_mark.length > 0
                && Arrays.asList(bean.agent_mark).contains("8")) {
            official_iv.setVisibility(View.VISIBLE);
        } else {
            official_iv.setVisibility(View.GONE);
        }
        //内容
        ans_content.setText(bean.qqa_content);
        //时间
        ans_time.setText(bean.qqa_createDate);
    }

    private void showStatus(QAStatus qaStatus) {
        //赞数
        ans_zan_count.setText(qaStatus.likenum);
        //点赞状态
        ans_zan_iv.setImageResource(qaStatus.isLike.equals("0") ? R.drawable.zan_gray : R.drawable.zan_green);

        isSelf = false;
        boolean isBestAnswer = qaStatus.isBestAnswer.equals("1");
        ans_best_iv.setVisibility(isBestAnswer ? View.VISIBLE : View.GONE);

        if (isSelf) {
            //有最佳答案的话就不显示采纳
            ans_caina.setVisibility(qaStatus.hasBestAnswer.equals("1") ? View.GONE : View.VISIBLE);
        }

        robot_useful.setText("有帮助(" + qaStatus.likenum + ")");
        robot_useless.setText("没帮助(" + qaStatus.dislikenum + ")");
        robot_useless.setChecked(qaStatus.isDislike.equals("1"));
        robot_useful.setChecked(qaStatus.isLike.equals("1"));

    }


    @Override
    protected Type getTypeToken() {
        return new TypeToken<List<FollowUpBean>>() {
        }.getType();
    }

    @Override
    protected int getItemLayout() {
        return R.layout.answer_detail_item_new;
    }

    @Override
    protected void setNetUtil() {
        netUtil = new NetUtil(this, JsonApi.ANSWER_DETAIL);
        netUtil.setParams("qid", qid);
        netUtil.setParams("qaid", qaid);
    }


    @Override
    protected void convert(ViewHolder holder, final FollowUpBean item) {

        if (holder.getPosition() == 0) {
            holder.getView(R.id.head_ly).setVisibility(View.VISIBLE);
        } else {
            holder.getView(R.id.head_ly).setVisibility(View.GONE);
        }

        //回答头像
        GlideUtil.loadCircle(context, item.avatar, (ImageView) holder.getView(R.id.avatar));
        //认证
        if (item.agent_mark != null && item.agent_mark.length > 0
                && Arrays.asList(item.agent_mark).contains("6")) {
            holder.getView(R.id.verify).setVisibility(View.VISIBLE);
        } else {
            holder.getView(R.id.verify).setVisibility(View.GONE);
        }
        //回答者
        holder.setText(R.id.name, item.qfu_active_user);
        //回答时间
        holder.setText(R.id.time, item.qfu_createdate);
        //回答内容
        holder.setText(R.id.content, item.qfu_content);

    }

    @Override
    protected void scrollToEnd() {
        super.scrollToEnd();
        if (scrollToEnd) {
            listView.smoothScrollToPosition(adapter.getCount() + 1);
            scrollToEnd = false;
        }
    }

    private void setClick() {
        ans_caina.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NetUtil netUtil = new NetUtil(AnswerDetailActivity.this, JsonApi.BESANSWER);
                netUtil.setParams("a_id", qaid);
                netUtil.setParams("q_id", qid);
                netUtil.postRequest("", new NetUtil.RequestStringListener() {

                    @Override
                    public void onComplete(String result) {
                        // 采纳
                        if (JSONUtil.isSuccess(result)) {
                            Intent intent = new Intent();
                            qaStatus.isBestAnswer = "1";
                            qaStatus.hasBestAnswer = "1";

                            intent.putExtra("qaStatus", qaStatus);
                            intent.setAction(Constant.ANSWER_TO_QUESTION);
                            sendBroadcast(intent);
                            ans_best_iv.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        });

        ans_zan_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginStatus()) {

                    NetUtil netUtil = new NetUtil(AnswerDetailActivity.this, JsonApi.PRAISE);
                    netUtil.setParams("qaid", qaid);
                    netUtil.setParams("qid", qid);
                    netUtil.postRequest("", new NetUtil.RequestStringListener() {
                        @Override
                        public void onComplete(String result) {
                            int qaLikeStatus = 0;
                            try {
                                JSONObject json = new JSONObject(JSONUtil
                                        .getData(result));
                                qaLikeStatus = json.getInt("qaLikeStatus");  //1 和 -1
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            ans_zan_iv.setImageResource(qaLikeStatus == 1 ? R.drawable.zan_green : R.drawable.zan_gray);
                            int likenum;
                            if (qaLikeStatus == 1) {

                                likenum = Integer.parseInt(qaStatus.likenum) + 1;
                                qaStatus.isLike = "1";

                            } else {
                                likenum = Math.max(0, Integer.parseInt(qaStatus.likenum) - 1);
                                qaStatus.isLike = "0";
                            }
                            qaStatus.likenum = likenum + "";
                            ans_zan_count.setText(qaStatus.likenum);
                            Intent intent = new Intent();
                            intent.setAction(Constant.ANSWER_TO_QUESTION);

                            intent.putExtra("qaStatus", qaStatus);

                            sendBroadcast(intent);
                        }
                    });
                }
            }
        });
    }


    public void parseRobot(final AnswerDetailBean.AnsInfoBean item) {
        //回答者
        robotName.setText(item.u_nick);
        robotTime.setText(item.qqa_createDate);
        robotContent.setText(item.qqa_content);
        robot_useful.setText("有帮助(" + item.qqa_like + ")");
        robot_useless.setText("没帮助(" + item.qqa_dislike + ")");
        robot_useless.setChecked(qaStatus.isDislike.equals("1"));
        robot_useful.setChecked(qaStatus.isLike.equals("1"));


        robot_useful.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (robot_useful.isChecked()) {
                    if (qaStatus.isDislike.equals("1")) {
                        qaStatus.isDislike = "0";
                        qaStatus.dislikenum = Math.max(0, Integer.parseInt(qaStatus.dislikenum) - 1) + "";
                    }

                }
                showZan(qaStatus);

            }
        });

        robot_useless.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (robot_useless.isChecked()) {
                    if (qaStatus.isLike.equals("1")) {
                        qaStatus.isLike = "0";
                        qaStatus.likenum = Math.max(0, Integer.parseInt(qaStatus.likenum) - 1) + "";
                    }
                }
                showDisLike(qaStatus);
            }
        });
    }

    private void showDisLike(final QAStatus item) {
        if (loginStatus()) {

            NetUtil netUtil = new NetUtil(AnswerDetailActivity.this, JsonApi.ANSWERDISLIKE);
            netUtil.setParams("qaid", qaid);
            netUtil.setParams("qid", qid);
            netUtil.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    int qaLikeStatus = 0;
                    try {
                        JSONObject json = new JSONObject(JSONUtil
                                .getData(result));
                        qaLikeStatus = json.getInt("qaLikeStatus");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (qaLikeStatus == 1) {
                        item.isDislike = 1 + "";
                        item.dislikenum = Integer.parseInt(item.dislikenum) + 1 + "";
                    } else {
                        item.isDislike = 0 + "";
                        item.dislikenum = Math.max(0, Integer.parseInt(item.dislikenum) - 1) + "";
                    }
                    Intent intent = new Intent();
                    intent.setAction(Constant.ANSWER_TO_QUESTION);
                     qaStatus = new QAStatus(item.isLike, item.isDislike,
                            item.dislikenum, item.likenum,
                            qid, item.qaid,
                            item.isBestAnswer, "0",
                            item.src);

                    intent.putExtra("qaStatus", qaStatus);

                    sendBroadcast(intent);
                    showStatus(qaStatus);
                }
            });
        }
    }

    private void showZan(final QAStatus item) {
        if (loginStatus()) {

            NetUtil netUtil = new NetUtil(AnswerDetailActivity.this, JsonApi.PRAISE);
            netUtil.setParams("qaid", qaid);
            netUtil.setParams("qid", qid);
            netUtil.postRequest("", new NetUtil.RequestStringListener() {
                @Override
                public void onComplete(String result) {
                    int qaLikeStatus = 0;
                    try {
                        JSONObject json = new JSONObject(JSONUtil
                                .getData(result));
                        qaLikeStatus = json.getInt("qaLikeStatus");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (qaLikeStatus == 1) {
                        item.isLike = 1 + "";
                        item.likenum = Integer.parseInt(item.likenum + "") + 1 + "";


                    } else {
                        item.isLike = 0 + "";
                        item.likenum = Math.max(0, Integer.parseInt(item.likenum) - 1) + "";
                    }

                    Intent intent = new Intent();
                    intent.setAction(Constant.ANSWER_TO_QUESTION);
                     qaStatus = new QAStatus(item.isLike, item.isDislike,
                            item.dislikenum, item.likenum,
                            qid, item.qaid,
                            item.isBestAnswer, "0",
                            item.src);

                    intent.putExtra("qaStatus", qaStatus);

                    sendBroadcast(intent);
                    showStatus(qaStatus);


                }
            });
        }

    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}
